package com.itwxz.forum.controller.pc;

import cn.dev33.satoken.session.SaTerminalInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.itwxz.common.core.redis.RedisCache;
import com.itwxz.forum.domain.po.UserOnline;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;


@Tag(name = "论坛在线用户信息Controller")
@Slf4j
@RestController
@RequestMapping("/forum/user-online")
public class ForumUserOnlineController {

    @Autowired

    private RedisCache redisCache;

    /**
     * 查询论坛在线用户列表
     */
    @Operation(summary = "查询论坛在线用户列表")
    @PreAuthorize("@ss.hasPermi('forum:online:list')")
    @GetMapping("/list")
    public SaResult list(int pageNum, int pageSize, String keyword) {
        int start = (pageNum - 1) * pageSize;

        List<String> idList = StpUtil.searchSessionId(keyword, start, pageSize, true);

        long total = StpUtil.searchSessionId("", 0, Integer.MAX_VALUE, true).size();

        String prefix = "satoken:login:session:";

        List<UserOnline> resultList = new ArrayList<>();
        for (String id : idList) {
            id = StrUtil.removePrefix(id, prefix);
            log.info(id);
            List<SaTerminalInfo> terminalList = StpUtil.getTerminalListByLoginId(id);
            for (SaTerminalInfo terminal : terminalList) {
                resultList.add(UserOnline.builder()
                        .loginId(id)
                        .token(terminal.getTokenValue())
                        .deviceType(terminal.getDeviceType())
                        .loginTime(DateUtil.date(terminal.getCreateTime()).toLocalDateTime())
                        .nickName((String) terminal.getExtra("nickName"))
                        .ipaddr((String) terminal.getExtra("ipaddr"))
                        .loginLocation((String) terminal.getExtra("loginLocation"))
                        .browser((String) terminal.getExtra("browser"))
                        .os((String) terminal.getExtra("os"))
                        .build());
            }
        }

        return SaResult.ok()
                .set("total", total)
                .set("rows", resultList)
                .set("msg", "查询成功");
    }

    @PreAuthorize("@ss.hasPermi('forum:online:kick')")
    @DeleteMapping("/kick/{userId}")
    public SaResult kickUser(@PathVariable String userId) {
        StpUtil.kickout(userId);
        return SaResult.ok();
    }
}
